//
//  UIImage++.swift
//  QBoss
//
//  Created by yiwanjun on 2020/8/27.
//  Copyright © 2020 com.qiyee.qboss. All rights reserved.
//

import Foundation

public extension UIImage {
    /// 压缩图片数据-不压尺寸
    ///
    /// - Parameters:
    ///   - maxLength: 最大长度
    /// - Returns:
    func compressImageOnlength(maxLength: Int) -> Data? {
        
        guard let vData = self.jpegData(compressionQuality: 1) else { return nil }
        if vData.count < maxLength {
            return vData
        }
        var compress:CGFloat = 0.9
        guard var data = self.jpegData(compressionQuality: compress) else { return nil }
        while data.count > maxLength && compress > 0.01 {
            compress -= 0.01
            data = self.jpegData(compressionQuality: compress)!
        }
        return data
    }
    /// 根据尺寸重新生成图片, 以高度为准
    ///
    /// - Parameter size: 设置的大小
    /// - Returns: 新图
    func imageWithNewSize(size: CGSize) -> UIImage? {
        var newImgSize: CGSize = size
        if self.size.height > size.height {
            let width = size.height / self.size.height * self.size.width
            newImgSize = CGSize(width: width, height: size.height)
        }

        UIGraphicsBeginImageContext(newImgSize)
        self.draw(in: CGRect(x: 0, y: 0, width: newImgSize.width, height: newImgSize.height))
        
        let theImage = UIGraphicsGetImageFromCurrentImageContext()
        
        UIGraphicsEndImageContext()
        
        guard let newImg = theImage else { return  nil}
        
        return newImg
        
    }
}


